package model

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	DB  *gorm.DB
	err error
)

func MysqlInit() {
	viper.GetIntSlice("../appconfig/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("配置文件读取失败")
	}
	user := viper.GetString("mysql.User")
	password := viper.GetString("mysql.Password")
	host := viper.GetString("mysql.Host")
	port := viper.GetString("mysql.Port")
	database := viper.GetString("mysql.Database")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, database)
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	} else {
		fmt.Println("数据库连接成功")
		fmt.Println(dsn)
	}
	err = DB.AutoMigrate(&User{}, &Shop{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据表迁移成功")
	}
}
